//
//  HNPublishProductController.m
//  shezhan
//
//  Created by admin on 16/8/25.
//  Copyright © 2016年 haoniu. All rights reserved.
//

#import "HNPublishProductController.h"

@interface HNPublishProductController ()<UIWebViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>
@property (nonatomic,retain) UIImagePickerController * imagePicker;
@end

@implementation HNPublishProductController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0) {
        self.edgesForExtendedLayout=UIRectEdgeNone;
    }
    
    _webViewUrl = [NSMutableString stringWithFormat:@"%@%@",url_Base,_urlPath];
    _webViewUrl = [NSMutableString stringWithFormat:@"%@",[_webViewUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest * _req = [NSURLRequest requestWithURL:[NSURL URLWithString:_webViewUrl]];
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 20, mainScreenSize.width, mainScreenSize.height-20)];
    [_webView loadRequest:_req];
    _webView.scrollView.bounces = NO;
    _webView.delegate = self;
    [_webView setBackgroundColor:[AppConfig colorWithHexString:@"#ececec"]];
    [self.view addSubview:_webView];
    
    NSLog(@"====%d",(int)mainScreenSize.height-20);
}
-(void)viewWillAppear:(BOOL)animated{
    [self.navigationController setNavigationBarHidden:YES];
}

#pragma -mark WebView
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"WebView erros is %@",error);
    if ([error code] == NSURLErrorCancelled) {
        return;
    }
    // 应用场景:加载从服务器上下载的文件,例如pdf,或者word,图片等等文件
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"error" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    [webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]];
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    // Disable user selection
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    // Disable callout
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
    //JS交互
    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"JavaScriptInterface"]=self;
}
- (BOOL)webView: (UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *_str = [[request URL] absoluteString];
    NSLog(@"=============123:%@",request);
    if ([[_str substringToIndex:5] isEqualToString:@"file:"]) {
        return YES;
    }else if ([_str isEqualToString:_webViewUrl]) {
        return YES;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma -mark HNPublishProductJSExport - 设置返回
//返回
-(void)HNPublishProductJSExportBack{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
        
    }else{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            dispatch_async(dispatch_get_main_queue(),^{
                NSLog(@"回归主线程");
                [self.view resignFirstResponder];
                [self.navigationController popViewControllerAnimated:YES];
            });
        });
    }
    NSLog(@"-------goBack---------");
}


-(NSString *)HNPublishProductJSExportReturnLoginName{
    return [[EMClient sharedClient] currentUsername];
}
#pragma -mark 设置退出/更换用户头像 HNSettingJSExport

-(void)HNSettingJSExportOutLogin{
    NSLog(@"HNSettingJSExportOutLogin");
//    __weak HNMyController *weakSelf = self;
//    [self showHudInView:self.view hint:NSLocalizedString(@"setting.logoutOngoing", @"loging out...")];
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        EMError *error = [[EMClient sharedClient] logout:YES];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [weakSelf hideHud];
//            if (error != nil) {
//                [weakSelf showHint:error.errorDescription];
//                NSLog(@"error.errorDescription = %@",error.errorDescription);
//            }
//            else{
//                [[ApplyViewController shareController] clear];
//                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
//            }
//        });
//    });
}


-(void)HNSettingJSExportOutChangeUserImage{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(),^{
            UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"更换照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择", @"拍照", nil];
            actionSheet.delegate = self;
            actionSheet.tag = 1001;
            [actionSheet showInView:self.webView];
            self.imagePicker = [[UIImagePickerController alloc]init];
            self.imagePicker.delegate = self;
            self.imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
            self.imagePicker.allowsEditing = YES;
        });
    });
}

#pragma mark - 判断设备是否有摄像头
- (BOOL) isCameraAvailable
{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
#pragma mark - UIActionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag==1001) {
        _imagePicker = [[UIImagePickerController alloc] init];
        _imagePicker.editing = YES;
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
        if (buttonIndex == 0)
        {
            //相册
            _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //[self presentModalViewController:_imagePicker animated:YES];
            [self presentViewController:_imagePicker animated:YES completion:nil];
        }else if (buttonIndex == 1){
            //照相机
            if ([self isCameraAvailable]) {
                _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                //[self presentModalViewController:_imagePicker animated:YES];
                [self presentViewController:_imagePicker animated:YES completion:nil];
            }else{
                [self showHint:@"该设备没有摄像头"];
            }
        }else
        {
            //取消
        }
    }
    
}
#pragma mark - UIImagePicker delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //[picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //UIImage *image = [[info objectForKey:UIImagePickerControllerEditedImage] retain];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [self performSelector:@selector(saveImage:) withObject:image afterDelay:0.5];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
//    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    //[picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//上传图片
-(void)saveImage:(UIImage *)image{
    NSLog(@"image = %@",image);
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:url_UpdateUserImage parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //压缩图片
        __block UIImage * changeImage = [self compressImage:image toTargetWidth:333];
        
        NSData *data = UIImagePNGRepresentation(changeImage);
    
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
        NSLog(@"上传进度");
        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //上传成功
        NSLog(@"上传成功");
        NSError *error;
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            return;
        }
        NSLog(@"==dict:%@",data);
        NSDictionary *userImageDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%@",[data objectForKey:@"imgUrl"]],@"imgUrl", nil];
        
        NSLog(@"userImageDic =  %@",userImageDic);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *dicStr = [NSString stringWithFormat:@"%@",[AppConfig dictionaryToJson:userImageDic]];
            NSLog(@"dicStr =  %@",dicStr);
            //调用JS 的方法
            NSString *str = [self.webView  stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"upLoadSuccess(%@);",dicStr]];
            
            NSLog(@"str =  %@",str);
        });
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上传失败
        NSLog(@"上传失败");
        NSLog(@"%@",error.description);
    }];
    
}

//压缩图片
- (UIImage *)compressImage:(UIImage *)sourceImage toTargetWidth:(CGFloat)targetWidth {
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    NSLog(@"width = %f,height = %f",width,height);
    
    CGFloat targetHeight = (targetWidth / width) * height;
    NSLog(@"targetWidth = %f targetHeight = %f",targetWidth,targetHeight);
    
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

@end
